from django.contrib.auth.models import User
from django.http.request import HttpRequest
from django.views.static import serve
from drf_spectacular.utils import extend_schema
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework.request import Request
from rest_framework.response import Response

from account.models import UserProfile
from account.serializers import (LoginSerializer, ResetPasswordSerializer,
                                 UserProfileSerializer)


# 处理yaml文件和log文件,serve这个视图中是下载的方式获取的
def static_serve(request: HttpRequest, path, document_root=None, show_indexes=False):
    resp = serve(request, path, document_root, show_indexes)

    # 如果访问的静态文件是日志文件,修改返回响应的响应头中Content-Type的值为text/css
    if resp.status_code == 200:
        if path.endswith(".log") or path.endswith(".yaml"):
            resp.headers["Content-Type"] = "text/css; charset=utf-8"

    return resp


# Create your views here.
class UserProfileViewSets(viewsets.GenericViewSet):
    @extend_schema(
        request=LoginSerializer, responses=UserProfileSerializer, tags=["Account"]
    )
    @action(methods=["POST"], detail=False, permission_classes=[AllowAny])
    def login(self, request: Request):
        # 实例化,实例化的时候传递视图接收到的数据
        serializer = LoginSerializer(data=request.data)
        # 视图接收到的数据,交给序列化器进行校验
        serializer.is_valid(raise_exception=True)

        # 在数据库中查找到数据(user就是在序列化器中经过检验之后的数据中存在)
        profile, is_created = UserProfile.objects.get_or_create(
            user=serializer.validated_data["user"]
        )

        # 通过序列化器生成响应数据
        serializer = UserProfileSerializer(profile)
        return Response(serializer.data)

    @extend_schema(request=ResetPasswordSerializer, tags=["Account"])
    @action(methods=["POST"], detail=False)
    def reset_password(self, request: Request):
        # 实例化,实例化的时候传递视图接收到的数据
        serializer = ResetPasswordSerializer(data=request.data)
        # 视图接收到的数据,交给序列化器进行校验
        serializer.is_valid(raise_exception=True)
        # 获取用户
        user: User = request.user
        # 重置密码
        user.set_password(serializer.validated_data["new_password"])
        # 将重置之后的密码保存到数据库中
        user.save()

        return Response({"code": 0, "msg": "密码重置成功！"})

    @extend_schema(responses=UserProfileSerializer, tags=["Account"])
    @action(methods=["GET"], detail=False)
    def get_user_profile(self, request: Request):
        # 在数据库中查询到对应用户的个人信息
        profile = UserProfile.objects.get(user=request.user)

        # 通过序列化器生成对应的响应数据
        serializer = UserProfileSerializer(profile)

        # 返回响应
        return Response(serializer.data)

    @extend_schema(
        # request=UserProfileSerializer,
        request={
            "multipart/form-data": {
                "type": "object",
                "properties": {
                    "head_img": {"type": "file"},
                    "nick_name": {"type": "string"},
                },
                "required": ["head_img", "nick_name"],
            }
        },
        responses=UserProfileSerializer,
        tags=["Account"],
    )
    @action(methods=["POST"], detail=False)
    def change_user_profile(self, request: Request):
        # 修改信息之前,必须先获取想要修改的用户信息
        profile = UserProfile.objects.get(user=request.user)

        # 接收请求的参数,还要知道是profile中的哪条记录
        serializer = UserProfileSerializer(profile, data=request.data)
        serializer.is_valid(raise_exception=True)

        # 将请求数据和model数据进行合并
        serializer.save()

        return Response(serializer.data)
